package com.deli.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.deli.springboot.entity.Book;
import com.deli.springboot.entity.ResultDo;
import com.deli.springboot.entity.ResultList;
import com.deli.springboot.service.BookServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/**
 * 书籍查询和新增
 */


@RestController
public class BookController {

    private static final Logger logger = LoggerFactory.getLogger(BookController.class);
    @Autowired
    private BookServiceImpl bookService;


    /**
     * 通过书名、状态查询图书
     *
     * @param book
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping(value = "book/find")
    public String findByExample(Book book, Integer pageNum, Integer pageSize) {
        ResultList<Book> resultList = new ResultList();
        if (null != book) {
            resultList.setSuccess(false);
            resultList.setErrorDescription("输入的查询参数book：" + book + " 有误");
            return JSON.toJSONString(resultList);
        }
        List<Book> books = bookService.findByExample(book, pageNum, pageSize);
        if (null != books && books.size() > 0) {
            resultList.setSuccess(true);
            resultList.setDataList(books);
            return JSON.toJSONString(resultList);
        }
        resultList.setSuccess(false);
        resultList.setErrorDescription("搜索不到结果");
        return JSON.toJSONString(resultList);
    }

    /**
     * 新增书籍（员工捐赠/内部购买）
     *
     * @param book
     * @return
     */
    @RequestMapping(value = "book/add")
    public String add(String book) {
        logger.info("go to BookController addMethod book param is " + book);
        Book bookPojo = JSON.parseObject(book, Book.class);
        ResultDo<Integer> result = new ResultDo<>();
        if (bookPojo.getcType() == 0 || bookPojo.getcType() == 1) {
            List<Book> books = bookService.findByExample(bookPojo, 1, 10);
            if (books != null && books.size() > 0) {
                result.setErrorDescription("该书存在，请重新输入");
                return JSON.toJSONString(result);
            }

            if (null != book && "" != JSON.toJSON(book)) {
                int add = bookService.add(bookPojo);
                if (add <= 0) {
                    result.setSuccess(false);
                    result.setErrorDescription("添加新书失败");
                    return JSON.toJSONString(result);
                } else {
                    result.setSuccess(true);
                    return JSON.toJSONString(result);
                }
            }
        }
        result.setSuccess(false);
        result.setErrorDescription("书籍的添加方式有误");
        return JSON.toJSONString(result);
    }
}

